<?php
namespace Kangcg\Application\Validate\Rules;

use Kangcg\Application\Validate\Validator;

trait RuleTrait
{
    public $message;

    protected function beforeRun(&$value) : bool{
        if($value === null || $value === ''){
            return false;
        }

        return true;
    }

    public function run(&$value, string $field, array $input, Validator $validator)
    {
        if($this->beforeRun($value) === false){
            return;
        }

        return $this->afterRun($value, $field, $input, $validator);
    }

    abstract protected function afterRun(&$value, string $field, array $input, Validator $validator);

    public function getMessage($attribute, $message = '', $text = null)
    {
        return str_replace([':attribute', ':message'], [$attribute, $message], $text ? $text : $this->message);
    }

    public function setRules($rules)
    {
        return $this->_rules = $rules;
    }

    public function isRule($rule) : bool
    {
        return in_array($rule, $this->_rules) || isset($this->_rules[$rule]);
    }

    public function extra($extra)
    {
        return $extra;
    }

    public function setConfig($config)
    {
        $config = $this->extra($config);
        if(is_iterable($config)){
            if(!($this->_reflectionClass instanceof \ReflectionClass)){
                $this->_reflectionClass =  new \ReflectionClass($this);
            }

            foreach ($config as $key => $value) {
                if(is_int($key) || !$this->_reflectionClass->hasProperty($key)) continue;
                if($this->_reflectionClass->getProperty($key)->isPublic()){
                    $this->{$key} = $value;
                }
            }
        }

        return $this;
    }

    private $_reflectionClass = null;
    private $_attributes = [];
    private $_rules;
}
